<?php
$myDataString = file_get_contents('/data.txt');
	//makes double(and triple) spaces single spaces. 
	$myDataString = preg_replace("'\s+'", " ", $myDataString);
	$myDataArray = explode("\n", $myDataString);
	
	$sortedMyDataArray[] = array();
	$i = 0;
	foreach($myDataArray as $value)
	{
		$sortedMyDataArray[$i] = explode(",", $value);
		$i++;
	}

	
	$database;
	try{
		//new connection
		$database = new PDO('sqlite:UserDB.sqlite');
		$database->setAttribute(PDO::ATTR_ERRMODE, PDO::ERRMODE_EXCEPTION);
	}catch(PDOException $e){
		die("Ett fel har inträffat: " . $e->getMessage());
	}
	
	$query = 'CREATE TABLE Position (pID INTEGER, longitude REAL, latitude REAL, description TEXT)';
	
	try{
		$stmt = $database->prepare($query);
		if(!$stmt->execute()){
			die("Gick inte att skapa tabell");
		}
	}catch(PDOException $e){
			die("FEL-->" . $e->getMessage());
		}
	
	foreach($sortedMyDataArray as $key=>$value){
		
		//Bad solution to remove whitespaces in start and end of string. 
		$value[0] = trim($value[0]);
		$value[1] = trim($value[1]);
		$value[2] = trim($value[2]);
		$value[3] = trim($value[3]);
		
		//In med data
		$q = 'INSERT INTO Position (pID, longitude, latitude, description) VALUES ("'.$value[2].'", "'.$value[0].'", "'.$value[1].'", "'.$value[3].'")';
		
		if(!$database->query($q)){
			die("fel vid insert");
		}
	}
	